package service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

public class VerificationCode {
    private int width = 50;
    private int height = 20;
    private Font font= new Font("宋体", Font.PLAIN,24);
    private Random r = new Random();
    private Color bgColor = new Color(255, 255, 255);
    private String text;

    public  BufferedImage getImage(){
        BufferedImage image = createImage();
        Graphics g = image.getGraphics();
        StringBuilder stringBuilder = new StringBuilder();

        for(int i = 0; i < 4; i++){
            stringBuilder.append(randomChar());
            g.setFont(font);
            g.setColor(randomColor());
            g.drawString(stringBuilder.toString(), width/4, height - 5);
        }
        this.text = stringBuilder.toString();
        drawLine(image);
        return image;
    }

    public String getText() {
        return text;
    }

    public static void output(BufferedImage image, OutputStream out) throws IOException{
        ImageIO.write(image, "JPEG", out);
    }

    private BufferedImage createImage(){
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(bgColor);
        g.fillRect(0, 0, width, height);
        return image;
    }

    public char randomChar(){
        String codes = "0123456789";
        return codes.charAt(r.nextInt(codes.length()));
    }

    public Color randomColor(){
        return new Color(r.nextInt(150),r.nextInt(150),r.nextInt(150));
    }

    public void drawLine(BufferedImage image){
        Graphics graphics = image.getGraphics();
        for(int i = 0; i < 3; i++){
            int x1 = r.nextInt(width);
            int y1 = r.nextInt(height);
            int x2 = r.nextInt(width);
            int y2 = r.nextInt(height);

            graphics.setColor(Color.BLACK);
            graphics.drawLine(x1, y1, x2, y2);
        }
    }
}
